<?php

class UserController extends BaseController
{

	function init()
	{
		/* Initialize action controller here */
		$request = $this->getRequest();
		$this->view->actionName = $request->getActionName();

		$authenticate = new Defined_Authenticate();
		if($authenticate->isLogged()===false){
			$link = '/'.$request->getControllerName().'/'.$this->view->actionName;
			$id = $request->getParam('id','');
			if ($id) $link .= '/id/'.$id;
			setcookie('referrer', $link,time()+30*24*60*60,'/');
			$this->_redirect ('/post/');
			exit;
		}
			
		$this->view->CP_MENU = $this->view->render('user/cp_menu.phtml');
		$this->load_header .= '<script type="text/javascript" src="'.JS_URL.'jquery.blockUI.js"></script>'."\n";
	}

	function indexAction(){
		$this->_redirect('/user/post/');
	}

	function listAction(){
		$mMotorSearch = new MotorSearch();

		$page = $this->_request->getParam('page',1);
		$page = $page ? intval($page):1;
		$rows_per_page = 5;
		$offset = ($page-1) * $rows_per_page;

		$list = $mMotorSearch->getMotors(' AND m.user_id='.$this->auth->id, 'ORDER BY m.updated_time DESC', $offset, $rows_per_page);
		$html = '';
		foreach ($list['result'] as $row){
			if($row['image'] && file_exists(UPLOAD.'default/item/'.$row['image']) ){
				$this->view->IMAGE = UPLOAD_DIR.'default/item/'.$row['image'];
			}else{
				$this->view->IMAGE = IMAGE_URL.'no_img.png';
			}

			$this->view->ID = $row['id'];
			if ($row['manu_name']=="Khác" && $row['manu_khac']!="Thương hiệu xe của bạn là gì?") $row['manu_name']=$row['manu_khac'];
			if ($row['model_name']=="Khác" && $row['model_khac']!="Model xe của bạn là gì? ") $row['model_name']=$row['model_khac'];
			$this->view->NAME = $row['manu_name'] . ' '.$row['model_name'];
			if ($this->view->NAME=="Khác Khác"&&($this->type==0)) $this->view->name = "Xe máy cũ";
			else if ($this->view->NAME=="Khác Khác"&&($this->type==1)) $this->view->name = "Ô tô cũ";
			$this->view->date = date('d/m/Y', strtotime($row['created_time']));
			if ($row['price']){
				$this->view->Price = number_format ($row['price'],0,'','.') ;//$row['price'] . ' Triệu';
			}else{
				$this->view->Price = 'Thỏa thuận';//$row['price_from'] .' Triệu - '. $row['price_to'].' Triệu';
			}

			$this->view->CITY_NAME = $row['city_name'];
			$this->view->Brand = $row['manu_name'];
			$this->view->Model = $row['model_name'];
			$this->view->STATUS = $row['active'];
			$this->view->PREMIUM = $row['premium'];
			$this->view->ALIAS = $row['alias'];

			$html .= $this->view->render('user/posts_item.phtml');
		}
		if ($html!=''){
			$this->view->LIST_POSTS = $html;
			$pager = LoadObject::startPaging();
			$sPaging_html = $pager->pager($list['total'], $rows_per_page, $page, 'search/paging.phtml');
			$this->view->PAGINATOR = $sPaging_html;
		}else{
			$this->view->LIST_POSTS = array ();
		}

	}
	function delAction(){
		$id = $this->getRequest()->getParam('id','');
		$mMotor = new Motor();

		$mt = $mMotor->getMotorByID($id, $this->auth->id);
		$num = $mMotor->delete($this->auth->id, $id);

		$this->_helper->viewRenderer->setNoRender();
		if($num>0){
			$config_img = Zend_Registry::get('config_site');
			$size = $config_img['default'];
			$imgs = array($mt['image'], $mt['image1'], $mt['image2']);
			foreach ($imgs as $img) {
				foreach ($size as $key=>$value) {
					if (file_exists(UPLOAD.'default/'.$key.'/'.$img))
						unlink(UPLOAD.'default/'.$key.'/'.$img);
				}
			}


			echo '<script>alert ("Xóa thành công"); window.location ="/user/list/";</script>' . "\n";
		}
		else{
			echo '<script>alert ("Xóa không thành công"); window.location ="/user/list/";</script>' . "\n";
		}

	}
	function postAction(){
		$this->load_header .= '<script type="text/javascript" src="'.JS_URL.'jquery.price_format.1.5.js"></script>';



		$id = $this->getRequest()->getParam('id','');
		$rules = array (
                'city_id'=>'req',
                'manu_id'=>'req',
                'model_id'=>'req',
                'style_id'=>'req',
                'year'=>'req',
                'kms'=>'req',
                'desc'=>'req',               
                'agree'=>'req'
                );
                $arrAlert=array(
                'city_id'=>'Vui lòng chọn thành phố.',             
                'manu_id'=>'Vui lòng chọn thương hiệu.',
                'model_id'=>'Vui lòng chọn model.',
                'style_id'=>'Vui lòng chọn dòng xe.',
                'year'=>'Vui lòng nhập năm sản xuất xe.',
                'kms'=>'Vui lòng nhập số Km sử dụng.',
                'desc'=>'Vui lòng mô tả xe.',
                'price'=>'Bạn phải cung cấp giá bán xe.',
                'image'=>'Không thể upload hình ảnh.',
                'image3'=>'File hình ảnh có lỗi.',
                'image2'=>'Vui lòng upload hình ảnh dưới 1MB!',
                'image1'=>'Vui lòng upload hình ảnh với định dạng .jpg  .gif .png!',
                'agree'=>'Bạn phải chấp nhận những điều khoản của website.',
                'captcha_code'=>'Mã bảo mật không chính xác!',
                'POST_FREE'=>'Để thực hiện chức năng này, vui lòng tiến hành thanh toán.'
                );

                if ($id && !$this->getRequest()->isPost()){

                	// $mMotor = new Motor();
                	$motor =  $this->view->MOTOR_INFO;//$mMotor->getMotorByID ($id, $this->auth->id);
                	if (POST_FREE || $motor['premium']==1){
                		$motor['desc'] = str_replace ('<br />', "\n", $motor['desc']);
                		$this->view->ID = $motor['id'];

                		$this->view->EDIT = 1;
                		$this->view->POST = $motor;
                	}else{
                		$this->_helper->viewRenderer->setNoRender();

                		echo '<script>alert ("'.$arrAlert['POST_FREE'].'"); window.location ="/user/list/";</script>' . "\n";

                	}

                }

                 
                if ($this->getRequest()->isPost()){
                	$post = $this->getRequest()->getPost();

                	$this->view->POST = $post;

                	$oValid = new Defined_Validation();


                	if ($post['type']==0){
                		unset ($rules['style_id']);
                	}
                	if (!isset($post['agree']) || $post['agree']==0){
                		$post['agree'] = '';
                	}
                	$oValid->rules = $rules;
                	//var_dump($oValid->rules);die;
                	$valid =  $oValid->validate($post);

                	if ($valid===true){

                		//captcha
                		//include_once  'static/captcha/securimage/securimage.php';
                		//$securimage = new Securimage();
                		if (strtoupper($post['captcha_code']) != $_SESSION['security_code']) {
                			$this->view->CALL_SCRIPT = 'alert ("'.$arrAlert['captcha_code'].'");' . "\n";

                		}
//                        unset ($_SESSION['security_code']);
                		$ALIAS_MANUFACTURE = $this->view->ALIAS_MANUFACTURE[$post['manu_id']];
                		$ALIAS_MODEL = $this->view->ALIAS_MODEL[$post['model_id']];
                		$ALIAS_CITY = $this->view->ALIAS_CITY[$post['city_id']];

                		$data = array (
                            'alias'=> $ALIAS_MANUFACTURE['alias'].'-'.$ALIAS_MODEL['alias'],
                            'user_id'=>$this->auth->id,                    
                            'manu_id'=> $ALIAS_MANUFACTURE['id'],
        					'manu_diffirent'=> $post['manu_diffirent'],
                            'model_id'=> $ALIAS_MODEL['id'],
        					'model_diffirent'=> $post['model_diffirent'],
                            'city_id'=> $ALIAS_CITY['id'],
                            'type'=>$post['type'],
                            'year'=>$post['year'],
                            'kms'=>$post['kms'],
                            'desc'=>str_replace ("\n", '<br />', $post['desc']),
                            'active'=>POST_FREE
                		);


                		if ($post['type']==1){
                			$ALIAS_STYLE = $this->view->ALIAS_STYLE[$post['style_id']];
                			$data['style_id'] = $ALIAS_STYLE['id'];
                		}
                		if ($post['price']>0){
                			$data['price'] = str_replace ('.', '', $post['price']);
                			$data['price_from'] = 0;
                			$data['price_to'] = 0;
                		}/*elseif($post['price_from']>=0 && $post['price_to']>0){
                		$data['price'] = 0;
                		$data['price_from'] = $post['price_from'];
                		$data['price_to'] = $post['price_to'];
                		}*/else{
                		$this->view->CALL_SCRIPT = 'alert ("'.$arrAlert['price'].'");' . "\n";
                		}

                		$upload = new Defined_Upload();

                		$data['image'] = $upload->doUpload('image', '');
                		if ( is_numeric($data['image']) ){
                   $this->view->CALL_SCRIPT = 'alert ("'.$arrAlert['image'.$data['image']].'");' . "\n";
                		}


                		$data['image1'] = $upload->doUpload('image1', '');
                		if ( is_numeric($data['image1']) ){
                			$this->view->CALL_SCRIPT = 'alert ("'.$arrAlert['image'.$data['image1']].'");' . "\n";
                		}

                		$data['image2'] = $upload->doUpload('image2', '');
                		if ( is_numeric($data['image2']) ){
                			$this->view->CALL_SCRIPT = 'alert ("'.$arrAlert['image'.$data['image2']].'");' . "\n";
                		}

                		if($this->view->CALL_SCRIPT==''){
                			if ($data['image']==''){
                				unset ($data['image']);
                			}
                			if ($data['image1']==''){
                				unset ($data['image1']);
                			}
                			if ($data['image2']==''){
                				unset ($data['image2']);
                			}

                			$mMotor = new Motor();
                			$data['kms'] = str_replace ('.', '', $post['kms']);

                			if ($post['id']>0){
                				$data['active'] =1;
                				$id = $mMotor->updateMotor($data, $post['id']);
                			}

                			else {
                				$id = $mMotor->insert($data);

                				$data['id'] =$id;
                				$this->alert($data);
                			}
                		}
                		else
                		$id=0;

                		if ($id>0){

                			if ($post['id']>0){
                				$this->_redirect('/user/list/');
                				exit;
                			}
                			/*
                    $countPostbyUser = $mMotor->countPostbyUser($this->auth->id);
                    if ($countPostbyUser==1){
                    $g='<!-- Google Code for Advertise MBX Conversion Page -->
                    <script type="text/javascript">
                    /* <![CDATA[ * /
                    var google_conversion_id = 1016290733;
                    var google_conversion_language = "vi";
                    var google_conversion_format = "3";
                    var google_conversion_color = "ffffff";
                    var google_conversion_label = "niZ0CIO5iAMQrbvN5AM";
                    var google_conversion_value = 0;
                    /* ]]> * /
                    </script>
                    <script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js">
                    </script>
                    <noscript>
                    <div style="display:inline;">
                    <img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1016290733/?label=niZ0CIO5iAMQrbvN5AM&amp;guid=ON&amp;script=0"/>
                    </div>
                    </noscript> ';
                    $this->view->Google_Conversion = $g;
                    }
                    */
                			if (POST_FREE==0){

                				$this->_helper->viewRenderer->setNoRender();
                				$this->load_header .= '<link rel="stylesheet" href="'.CSS_URL.'thickbox.css" type="text/css" media="screen" />';
                				$this->load_header .= '<script type="text/javascript" src="'.JS_URL.'thickbox.js"></script>';
                				$this->view->ID = $id;

                				$this->view->USERNAME = $this->auth->last_name .' '.$this->auth->first_name;
                				$this->view->EMAIL = $this->auth->email;
                				$this->view->CITY_NAME = $ALIAS_CITY['name'];//$this->auth->city_name;
                				$this->view->MOBILE = $this->auth->mobile;
                				$this->view->PHONE = $this->auth->phone;
                				$msg = $this->view->render('user/success.phtml');

                				$msg = str_replace ('"', "'", $msg);
                				$msg = str_replace ("\r\n", "", $msg);
                				$msg = str_replace ("\n", "", $msg);
                				$msg = preg_replace('/\s\s+/', ' ', $msg);

                				$this->view->CALL_SCRIPT = '
                            jQuery.blockUI({ 
                                message: "'.$msg. '",
                                css: { top:"100px", width: "385px", height:"365px"}
                            })';
                                /*Paypal*/
                                $this->view->ID = $id;
                                $this->view->USERNAME=$this->auth->email;
                                $this->view->MOTOR_CODE = str_pad($id, 6 , "0", STR_PAD_LEFT);
                                if ($this->type){
                                    $this->view->PAYMENT_CODE = 'MBX-'.$this->view->MOTOR_CODE.'-Y';
                                    $this->view->USD_PAYMENT_PRICE = '15.00';
                                    $this->view->VND_PAYMENT_PRICE = '300.000';
                                }else{
                                    $this->view->PAYMENT_CODE = 'MBX-'.$this->view->MOTOR_CODE.'-X';
                                    $this->view->USD_PAYMENT_PRICE = '5.00';
                                    $this->view->VND_PAYMENT_PRICE = '100.000';
                                }
                                $this->view->KEY = base64_encode($this->auth->email.'-'.$id);
                                /*End Paypal*/
                				echo $this->view->render('user/post_success.phtml');
                				 
                			}else{

                				$link = $this->view->translate('by_type_detail_'.$this->type);
                				$link = str_replace ('([a-zA-Z0-9-_]+)',$data['alias'], $link);
                				$link = str_replace ('([0-9]+)',$id, $link);
                				$this->view->LINK = $link;
                				$msg = $this->view->render('user/success1.phtml');
                				$msg = str_replace ('"', "'", $msg);
                				$msg = str_replace ("\r\n", "", $msg);
                				$msg = str_replace ("\n", "", $msg);
                				$msg = preg_replace('/\s\s+/', ' ', $msg);
                				$this->view->CALL_SCRIPT = '
                        jQuery.blockUI({ 
                            message: "' .$msg. '",
                            css: { width: "385px", height:"145px"}
                        })';                        

                			}

                		}
                	}else{
                		$this->view->CALL_SCRIPT = 'alert ("'.$arrAlert[$valid].'");' . "\n";
                	}
                }

                //echo $this->view->render('register/step2.phtml');
	}
	public function editAction(){
		$this->load_header .= '<script type="text/javascript" src="'.JS_URL.'jquery.maskedinput-1.3.min.js"></script>';
		$this->load_header .= '<script type="text/javascript">jQuery(function(){
   $("#birthdate").mask("99/99/9999",{placeholder:" "});   
});</script>';
		$request=$this->getRequest();

		if ($request->isPost()){

			$post = $request->getPost();

			$post['birthdate'] = str_replace('/','-', $post['birthdate']);

			$rules = array (
                'first_name'=>'req',
                'last_name'=>'req',                
                'birthdate'=> array ('req'=>true, 'date'=>'d-m-Y'),
                'address'=>'req',
                'city_id'=>'req',
                'mobile'=>'req',
			//'phone'=>'req',
			//'agree'=>'req'
			);
			$arrAlert=array(
                'first_name'=>'Vui lòng nhập Tên',
                'last_name'=>'Vui lòng nhập Họ',                
                'birthdate'=> 'Ngày sinh không chính xác. Vui lòng kiểm tra lại!',
                'address'=>'Địa chỉ bắt buộc phải nhập',
                'city_id'=>'Bạn chưa chọn thành phố',
                'mobile'=>'Số di động chưa được nhập',
			//'phone'=>'Số điện thoại chưa nhập',
                'agree'=>'Bạn phải chấp nhận những điều khoản của website',
                'confirm_password'=>'Mật khẩu không trùng khớp. Vui lòng kiểm tra lại',
                'success'=>'Cập nhật thành công'
                );
                $username = $post['email'];
                if ($post['password']!='' && $post['confirm_password'] !=''){
                	$rules['confirm_password'] = array ('equalTo'=>$post['password']) ;
                	$passwd = md5($post['password']);
                }else{
                	unset ($post['password']);
                	$passwd = $this->auth->password;
                }
                /*if (!isset($post['agree']) || $post['agree']==0){
                 $post['agree'] = '';
                 }*/
                $oValidation = new Defined_Validation($rules);
                //var_dump($oValidation->rules);die;

                $valid = $oValidation->validate($post);

                if ($valid===true){
                	$date = explode ('-', $post['birthdate']);
                	$post['birthdate'] = $date[2] . '-' . $date[1] .'-'.$date[0];
                	unset ($post['confirm_password']);
                	unset ($post['agree']);

                	$mUsers = new User();

                	$post['password'] = $passwd;

                	$id = $mUsers->update ($post, 'id='.$this->auth->id);
                	if($id>0){
                		$authenticate = new Defined_Authenticate();
                		$authenticate->logout();
                		if($authenticate->login($username, $passwd)===true){
                			$this->auth = $authenticate->getIdentity();
                		}

                		$this->view->CALL_SCRIPT = 'alert ("'.$arrAlert['success'].'");window.location="/user/edit/";' . "\n";
                	}

                }else{
                	$this->view->CALL_SCRIPT = 'alert ("'.$arrAlert[$valid].'");' . "\n";
                }
		}
		$this->view->CHECKFORM = Common::check_input('first_name,last_name,birthdate,address,city_id,mobile','edit_user');// Check input

		$this->view->FNAME = $this->auth->first_name;
		$this->view->LNAME = $this->auth->last_name;
		$this->view->BIRTHDATE = date('d-m-Y', strtotime($this->auth->birthdate));
		$this->view->SEX = $this->auth->sex;
		$this->view->ADDRESS = $this->auth->address;
		$this->view->MOBILE = $this->auth->mobile;
		$this->view->PHONE = $this->auth->phone;
		$this->view->EMAIL = $this->auth->email;
		$this->view->CITY = $this->auth->city_id;
			


	}//editAction
	function alert ($post){
		// Kiểm tra xem có trùng với yêu cầu tìm kiếm, nếu trùng send email
		if (intval($post['price'])>0){
			$sWhere4 = '( price_from=0 OR price_from<='.$post['price'].') and ( price_to=0 OR price_to>='.$post['price'].')';
		}else{
            $sWhere4 = '1';
		
		}
		$sWhere1 = 'manu_id='.$post['manu_id'];
		$sWhere2 = 'model_id='.$post['model_id'];
		$sWhere3 = 'city_id='.$post['city_id'];

		$sWhere5 = $sWhere1 .' and '. $sWhere2;
		$sWhere6 = $sWhere1 .' and '. $sWhere3;
		$sWhere7 = $sWhere1 .' and '. $sWhere4;
		$sWhere8 = $sWhere2 .' and '. $sWhere3;
		$sWhere9 = $sWhere2 .' and '. $sWhere4;
		$sWhere10= $sWhere3 .' and '. $sWhere4;
		$sWhere11= $sWhere5 .' and '. $sWhere3;
		$sWhere12= $sWhere5 .' and '. $sWhere4;
		$sWhere13= $sWhere6 .' and '. $sWhere4;
		$sWhere14= $sWhere8 .' and '. $sWhere4;
		$sWhere15= $sWhere5 .' and '. $sWhere10;

		$sWhere1 .= ' and model_id=0 and city_id=0 and price_from=0 and price_to=0';
		$sWhere2 .= ' and manu_id=0 and city_id=0 and price_from=0 and price_to=0';
		$sWhere3 .= ' and model_id=0 and manu_id=0 and price_from=0 and price_to=0';
		$sWhere4 .= ' and model_id=0 and city_id=0 and manu_id=0';

		$sWhere5 .= ' and city_id=0 and price_from=0 and price_to=0';
		$sWhere6 .= ' and model_id=0 and price_from=0 and price_to=0';
		$sWhere7 .= ' and model_id=0 and city_id=0';
		$sWhere8 .= ' and manu_id=0 and price_from=0 and price_to=0';
		$sWhere9 .= ' and city_id=0 and manu_id=0';
		$sWhere10 .= ' and model_id=0 and manu_id=0';

		$sWhere11 .= ' and price_from=0 and price_to=0';
		$sWhere12 .= ' and city_id=0';
		$sWhere13 .= ' and model_id=0';
		$sWhere14 .= ' and manu_id=0';

		$strWhere = "active=1 AND email<>'".$this->auth->email."' AND type=".$this->type." AND (($sWhere1) OR ($sWhere2) OR ($sWhere3) OR ($sWhere4) OR ($sWhere5) OR ($sWhere6) OR ($sWhere7) OR ($sWhere8) OR ($sWhere9) OR ($sWhere10)"
		."OR ($sWhere11) OR ($sWhere12) OR ($sWhere13) OR ($sWhere14) OR ($sWhere15))";

		$mAlert = new Alert();
		$arrAlert=$mAlert->getAlert($strWhere,'id','desc',0,'all', true);

		$link = $this->view->translate('by_type_detail_'.$this->type);
		$link = str_replace ('([a-zA-Z0-9-_]+)', $post['alias'], $link);
		$link = str_replace ('([0-9]+)', $post['id'], $link);

		$this->view->LINK = '<a href="'.DOMAIN.$link.'" target="_blank">Xem chi tiết tin bán xe</a>';

		$content=$this->view->render('mail/content.phtml');
		if(count($arrAlert)>0){
			$mEmail=new Mail();
			foreach($arrAlert as $data){
				if($data['email']=='') continue;
				if($data['email']!=''){
					$mEmail->sendEmail($data['email'],EMAIL_INFO,'Có tin bán xe phù hợp với nhu cầu tìm kiếm của bạn',$content);
					$mAlert->tracking_alert ($post['id'],$data['id'], 'Có tin bán xe phù hợp với nhu cầu tìm kiếm của bạn', $this->view->LINK);
				}
			}
		}
	}
}